package com.project.controller.file;

import com.project.controller.BaseController;
import com.project.dto.Result;
import com.project.service.MinioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @description: minio控制器
 **/
@Api(tags = {"文件上传、下载、预览接口"})
@RequestMapping("/minio")
@RestController
@Slf4j
public class MinioController extends BaseController {

    @Resource
    private MinioService minioService;

    @ApiOperation("上传文件")
    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file) {
        try {
            String contentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(Objects.requireNonNull(fileName).lastIndexOf("."));

            InputStream inputStream = file.getInputStream();
            minioService.putObject(objectName, inputStream, contentType);
            inputStream.close();
            return success(objectName);
        } catch (Exception e) {
            log.error("上传文件错误:", e.getMessage());
            return error("上传文件错误");
        }
    }

    @ApiOperation("预览文件")
    @GetMapping("/preview")
    public Result preview(String fileName) {
        String result = minioService.presignedGetObject(fileName);
        return success(result);
    }

    /**
     * 下载文件
     *
     * @param fileName   文件名
     */
    @ApiOperation(value = "下载文件",produces = "application/octet-stream")
    @GetMapping("/download")
    public Result download(String fileName, HttpServletResponse response) {
        minioService.downloadFile(fileName, response);
        return success();
    }

    /**
     * 删除
     *
     * @param fileName   文件名
     * @return 删除成功
     */
    @ApiOperation("删除文件")
    @GetMapping("/delete")
    public Result delete(String fileName) {
        boolean isRemove = minioService.removeObject(fileName);
        return success(isRemove);
    }
}
